package cuiyt.juc.pc;

/**
 * @author cyt
 * @create 2020-04-29 20:40
 */


// 示意生产者、消费者问题
public class demo02 {
    public static void main(String[] args) {
        data1 data = new data1();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }
}
class data1 {
    private Integer number = 0;
    public synchronized void increment() throws InterruptedException {
        while (number != 0) {
            this.wait();
            // 等待
        }
        number++;
        System.out.println(Thread.currentThread().getName() + "->" + number);
        // 通知
        this.notifyAll();
    }

    public synchronized void decrement() throws InterruptedException {
        while (number == 0) {
            this.wait();
            // 等待
        }
        number--;
        System.out.println(Thread.currentThread().getName() + "->" + number);
        // 通知
        this.notifyAll();
    }
}
